package com.cn.wanxi.service.impl;

import com.cn.wanxi.dao.UserDao;
import com.cn.wanxi.dao.impl.UserImpl;
import com.cn.wanxi.model.UserModel;
import com.cn.wanxi.service.IUserService;

import java.util.List;

/**
 * 调用数据实现层
 */
public class UserServiceImpl implements IUserService {
    /**
     * 首先判断当前用户名是否存在，
     * 如果存在，则提示当前用户很受欢迎，请换一个
     * 否则可以正常注册
     *
     * @param userModel
     * @return
     */
    @Override
    public String register(UserModel userModel) {
        UserDao userDao = new UserImpl();
        UserModel model = userDao.findByUsername(userModel.getUsername());
        if (model != null) {
            return "isHave";
        } else {
            int result = userDao.register(userModel);
            return result == 1 ? "success" : "error";
        }

    }

    /**
     * 登录：
     * 1.判断当前用户输入的验证码是否正确
     * 2.判断当前用户输入的用户名和密码是否正确
     *
     * @param userModel
     * @return
     */
    @Override
    public String login(UserModel userModel) {
        String result = "";
        if (!userModel.getCode().equals(userModel.getSessionCode())) {

            result = "error_code";
        } else {
            //判断用户名和密码是否正确
            UserDao userDao = new UserImpl();
            UserModel model = userDao.findByUsernameAndPassword(userModel);
            if (model != null) {
                result = "success";
            } else {
                result = "error";
            }
        }

        return result;
    }

    @Override
    public List<UserModel> findAll(UserModel userModel) {
        UserDao userDao = new UserImpl();
        return userDao.findAll(userModel);
    }

    @Override
    public String del(Integer id) {
        UserDao userDao = new UserImpl();
        return userDao.del(id) == 1 ? "success" : "error";
    }

    @Override
    public UserModel findById(Integer id) {
        UserDao userDao = new UserImpl();
        return userDao.findById(id);
    }

    @Override
    public String edit(UserModel userModel) {
        //首先判断当前要修改的用户名是否存在
//        如果存在，则不能修改，否则直接修改
        UserDao userDao = new UserImpl();
        UserModel model = userDao.findByUsernameForEdit(userModel);
        if (model != null) {
            return "isHave";
        } else {
            return userDao.edit(userModel) == 1 ? "success" : "error";
        }
    }

    @Override
    public int getCount(UserModel userModel) {
        UserDao userDao = new UserImpl();
        return userDao.getCount(userModel);
    }
}
